import * as fs from 'fs';
import * as path from 'path';

export interface BuilderRefactorResult {
  success: boolean;
  message: string;
  builderClass?: string;
  builderFile?: string;
  modifiedConstructors: number;
  refactorDetails?: string[];
  errors?: string[];
}

/**
 * Builder模式重构器 - 将多参数构造函数重构为Builder模式
 */
export class BuilderPatternRefactor {

  async introduceBuilder(
    filePath: string,
    minParameterCount: number = 3,
    builderClassName?: string
  ): Promise<BuilderRefactorResult> {
    const result: BuilderRefactorResult = {
      success: false,
      message: '',
      modifiedConstructors: 0,
      refactorDetails: [],
      errors: []
    };

    try {
      console.error(`[BuilderPatternRefactor] 开始Builder模式重构`);
      
      const content = fs.readFileSync(filePath, 'utf-8');
      const className = this.extractClassName(content);
      
      if (!className) {
        result.errors?.push('无法识别类名');
        result.message = '无法识别类名';
        return result;
      }

      const finalBuilderName = builderClassName || `${className}Builder`;
      
      // 分析构造函数
      const constructors = this.extractConstructors(content, className);
      const complexConstructors = constructors.filter(c => c.parameters.length >= minParameterCount);
      
      if (complexConstructors.length === 0) {
        result.success = true;
        result.message = '没有找到需要重构的复杂构造函数';
        return result;
      }

      // 提取字段信息
      const fields = this.extractFields(content);
      
      // 生成Builder类
      const builderClass = this.generateBuilderClass(finalBuilderName, className, fields, this.extractPackageName(content));
      
      // 创建Builder文件（作为内部类或单独文件）
      const builderFile = path.join(path.dirname(filePath), `${finalBuilderName}.java`);
      fs.writeFileSync(builderFile, builderClass, 'utf-8');
      
      result.builderClass = builderClass;
      result.builderFile = builderFile;
      result.modifiedConstructors = complexConstructors.length;
      result.success = true;
      result.message = `成功生成Builder类 ${finalBuilderName}`;
      result.refactorDetails?.push(`创建Builder文件: ${builderFile}`);

    } catch (error) {
      result.errors?.push(`Builder模式重构失败: ${error}`);
      result.message = `Builder模式重构失败: ${error}`;
    }

    return result;
  }

  private extractConstructors(content: string, className: string): Array<{parameters: Array<{type: string, name: string}>, fullSignature: string}> {
    const constructors: Array<{parameters: Array<{type: string, name: string}>, fullSignature: string}> = [];
    
    // 匹配构造函数的正则表达式
    const constructorPattern = new RegExp(`public\\s+${className}\\s*\\(([^)]*)\\)`, 'g');
    
    let match;
    while ((match = constructorPattern.exec(content)) !== null) {
      const parametersString = match[1];
      const parameters = this.parseParameters(parametersString);
      
      constructors.push({
        parameters,
        fullSignature: match[0]
      });
    }
    
    return constructors;
  }

  private parseParameters(parametersString: string): Array<{type: string, name: string}> {
    const parameters: Array<{type: string, name: string}> = [];
    
    if (!parametersString.trim()) {
      return parameters;
    }

    const paramParts = parametersString.split(',');
    
    for (const part of paramParts) {
      const trimmed = part.trim();
      const match = trimmed.match(/^(.+)\s+(\w+)$/);
      if (match) {
        parameters.push({
          type: match[1].trim(),
          name: match[2].trim()
        });
      }
    }
    
    return parameters;
  }

  private extractFields(content: string): Array<{type: string, name: string}> {
    const fields: Array<{type: string, name: string}> = [];
    
    // 匹配字段声明的正则表达式
    const fieldPattern = /^\s*(?:private|protected|public)\s+(\w+(?:<[^>]+>)?(?:\[\])*)\s+(\w+)/gm;
    
    let match;
    while ((match = fieldPattern.exec(content)) !== null) {
      fields.push({
        type: match[1],
        name: match[2]
      });
    }
    
    return fields;
  }

  private generateBuilderClass(builderName: string, targetClassName: string, fields: Array<{type: string, name: string}>, packageName: string): string {
    let content = '';
    
    if (packageName) {
      content += `package ${packageName};\n\n`;
    }
    
    content += `/**\n`;
    content += ` * Builder类 - 自动生成\n`;
    content += ` */\n`;
    content += `public class ${builderName} {\n\n`;
    
    // 私有字段
    for (const field of fields) {
      content += `    private ${field.type} ${field.name};\n`;
    }
    content += '\n';
    
    // Builder方法
    for (const field of fields) {
      const methodName = field.name;
      content += `    public ${builderName} ${methodName}(${field.type} ${field.name}) {\n`;
      content += `        this.${field.name} = ${field.name};\n`;
      content += `        return this;\n`;
      content += `    }\n\n`;
    }
    
    // build方法
    content += `    public ${targetClassName} build() {\n`;
    content += `        return new ${targetClassName}(`;
    const paramNames = fields.map(f => f.name).join(', ');
    content += paramNames;
    content += `);\n`;
    content += `    }\n`;
    
    content += `}\n`;
    
    return content;
  }

  private extractClassName(content: string): string | null {
    const match = content.match(/(?:public\s+)?class\s+(\w+)/);
    return match ? match[1] : null;
  }

  private extractPackageName(content: string): string {
    const match = content.match(/package\s+([^;]+);/);
    return match ? match[1].trim() : '';
  }
}